//
//  CZRecentVC.m
//  CZWeiXin
//
//  Created by Alvechen on 16/4/13.
//  Copyright © 2016年 alvechen. All rights reserved.
//

#import "CZRecentVC.h"
#import "CZChatVC.h"
#import "CZGroupChatVC.h"
#import "CZXMPPRoomManager.h"

@interface CZRecentVC ()<XMPPStreamDelegate,XMPPvCardAvatarDelegate>

///聊天记录查询结果控制器
@property (nonatomic,strong) NSFetchedResultsController  *fetchedResultsController;

@end

@implementation CZRecentVC

- (NSFetchedResultsController *)fetchedResultsController{
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    //实例化
    
    //存储器
    XMPPMessageArchivingCoreDataStorage *storage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
    
    //查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPMessageArchiving_Contact_CoreDataObject"];
    
    XMPPJID *jid = [CZXMPPManager shareInstance].xmppStream.myJID;
//    条件(谓词)@"bareJidStr == %@ && streamBareJidStr = %@",self.jid.bare,myJID.bare
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@",jid.bare];
    
    //排序描述器
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"mostRecentMessageTimestamp" ascending:NO];
    request.sortDescriptors = @[sortDesc];
    request.predicate = predicate;
    
    //创建查询结果控制器
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:storage.mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    //执行查询
    NSError *error = nil;
    [_fetchedResultsController performFetch:&error];
    
    
    //打印最近联系人结果
    for (XMPPMessageArchiving_Contact_CoreDataObject *aRecent in _fetchedResultsController.fetchedObjects) {
        
        
        //打印聊天信息
        NSLog(@"%@-%@",aRecent.bareJidStr,aRecent.mostRecentMessageBody);
        
        
        //主动加入所有的群
        
        //房间:ios8room@itcasts.im.itcast.cn
        //人:lisi@im.itcast.cn
        
        //如果jidStr不包含"@im.itcast.cn",则是房间
//        if (![aRecent.bareJidStr containsString:@"@im.zhigong.com"]) {
//            
//            [[CZXMPPRoomManager shareInstance] joinRoCreateRoomWithJid:aRecent.bareJid nickName:@"小三"];
//        }
        
        
        
    }
    
    return _fetchedResultsController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        [self jidWithResourceForJidstr:@"lisi@im.itcast.cn"];
//    });
    
    
    
    
//    [self fetchedResultsController];
    
    //成为流代理
    [[CZXMPPManager shareInstance].xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //成为个人资料头像模块代理
    [[CZXMPPManager shareInstance].xmppvCardAvatarModule addDelegate:self delegateQueue:dispatch_get_main_queue()];
    

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    //把执行线传进来的参数转对应类型
    XMPPMessageArchiving_Contact_CoreDataObject *aRecent = sender;
    
    //单聊
    if ([segue.identifier isEqualToString:@"chat"]) {
        //聊天控制器
        CZChatVC *chatVC = segue.destinationViewController;
        
        //赋值JID给聊天控制器
//        if ([self jidWithResourceForJidstr:aRecent.bareJidStr].resource) {
//            chatVC.jid = [self jidWithResourceForJidstr:aRecent.bareJidStr];
//        }else{
//            
//            chatVC.jid = aRecent.bareJid;
//        }
        
        chatVC.resourceJid = [self jidWithResourceForJidstr:aRecent.bareJidStr];
        chatVC.jid = aRecent.bareJid;
        
    }else{
    
        //聊天控制器
        CZGroupChatVC *groupChatVC = segue.destinationViewController;
        
        //赋值JID给聊天控制器
        if ([self jidWithResourceForJidstr:aRecent.bareJidStr].resource) {
            groupChatVC.jid = [self jidWithResourceForJidstr:aRecent.bareJidStr];
        }else{
            
            groupChatVC.jid = aRecent.bareJid;
        }
        
    }
    
    
    
    
    
    
    
//    //聊天控制器
//    CZChatVC *chatVC = segue.destinationViewController;
//    //获取选中的索引
//    NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
//    
//    //取出当前选中的对应的联系人对象
//    XMPPMessageArchiving_Contact_CoreDataObject *aRecent = [self.fetchedResultsController objectAtIndexPath:indexPath];
//    
//    //赋值JID给聊天控制器
//    if ([self jidWithResourceForJidstr:aRecent.bareJidStr].resource) {
//        chatVC.jid = [self jidWithResourceForJidstr:aRecent.bareJidStr];
//    }else{
//    
//        chatVC.jid = aRecent.bareJid;
//    }
    
    
    
}


#pragma mark - funcs

- (void)fetchData{
    
    //隔一段时间再去取,让数据库保存好了,才能取到最新数据
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //重新获取数据
        [self.fetchedResultsController performFetch:nil];
        //刷新表格
        [self.tableView reloadData];
        
    });
    
    
}

/**
 * 根据jid字符串返回带有resource的jid对象,   lisi@im.itcast.cn  --> "lisi@im.itcast.cn/resource"
 */
- (XMPPJID *)jidWithResourceForJidstr:(NSString *)jidstr{

    
    //存储器
    XMPPRosterCoreDataStorage *storage = [XMPPRosterCoreDataStorage sharedInstance];
    
    //查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPResourceCoreDataStorageObject"];
    //条件(谓词),根据jidstr查对应用在线联系人
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"jidStr CONTAINS %@",jidstr];
    
    //排序描述器
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"jidStr" ascending:YES];
    request.sortDescriptors = @[sortDesc];
    request.predicate = predicate;
    
    //创建查询结果控制器
    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:storage.mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    //执行查询
    NSError *error = nil;
    [fetchedResultsController performFetch:&error];
    
    for (XMPPResourceCoreDataStorageObject *aResource in fetchedResultsController.fetchedObjects) {
        
        //打印订阅情况
        NSLog(@"%@",aResource.jidStr);
    }
    
    //资源
    XMPPResourceCoreDataStorageObject *aResource = fetchedResultsController.fetchedObjects.firstObject;

    //带有资源的jid
    return aResource.jid;
    
}

#pragma mark - UI事件

/**
 * 开启群聊
 */
- (IBAction)groupChatClick:(id)sender {
    
    //房间JID:   iOS8Room@itcasts.im.itcast.cn
    XMPPJID *roomJid = [XMPPJID jidWithUser:@"iOS8Room" domain:@"zhigong.im.zhigong.com" resource:nil];
    
    //加入或创建
    [[CZXMPPRoomManager shareInstance] joinRoCreateRoomWithJid:roomJid nickName:@"小三"];
    
}

/// 注销

- (IBAction)logOut:(id)sender {
    /*
        SEND: <presence type="unavailable"><status>Logged Out</status><x xmlns="vcard-temp:x:update"><photo/></x></presence>
     */
//    NSXMLElement *body = [NSXMLElement elementWithName:@"status"];
//    [body setStringValue:@"Logged Out"];
//
//    NSXMLElement *mes = [NSXMLElement elementWithName:@"presence"];
//    [mes addAttributeWithName:@"type" stringValue:@"unavailable"];
//    [mes addChild:body];
//    
//    [[CZXMPPManager shareInstance].xmppStream sendElement:mes];
    
    
    /*
        SEND: <presence type="unavailable"><x xmlns="vcard-temp:x:update"><photo>9d35ed2764070024be661a228b11bf87b6b791b7</photo></x></presence>
     */
    // 通知用户下线
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    [[CZXMPPManager shareInstance].xmppStream sendElement:presence];
    // 与服务器断开连接
    [[CZXMPPManager shareInstance].xmppStream disconnect];
    
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UITableViewController *loginVC = [sb instantiateViewControllerWithIdentifier:@"loginVC"];
    [UIApplication sharedApplication].keyWindow.rootViewController = loginVC;
    
}




#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fetchedResultsController.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_recent"];
    
    //取出数据
    XMPPMessageArchiving_Contact_CoreDataObject *aRecent = self.fetchedResultsController.fetchedObjects[indexPath.row];
    
    //赋值数据
    UIImageView *avatarImgV = [cell viewWithTag:100];
    //使用个人资料头像模块获得头像
    NSData *avatarData = [[CZXMPPManager shareInstance].xmppvCardAvatarModule photoDataForJID:aRecent.bareJid];
    
    if (avatarData) {
        avatarImgV.image = [UIImage imageWithData:avatarData];
    }else{
        
        //默认头像
        avatarImgV.image = [UIImage imageNamed:@"DefaultHead"];
        
    }

    
    //账号
    UILabel *acountLb = [cell viewWithTag:101];
    acountLb.text = aRecent.bareJidStr;
    
    //最近一条消息
    UILabel *recentMsgLb = [cell viewWithTag:102];
    recentMsgLb.text = aRecent.mostRecentMessageBody;
    
    //时间戳
    UILabel *timeLb = [cell viewWithTag:103];
    
    //格式化
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"MM-dd HH:mm";
    
    NSString *dateStr = [dateF stringFromDate:aRecent.mostRecentMessageTimestamp];
    
    timeLb.text = dateStr;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    //取出数据
    XMPPMessageArchiving_Contact_CoreDataObject *aRecent = self.fetchedResultsController.fetchedObjects[indexPath.row];
    
    //判断单聊或群聊
    
    //房间:ios8room@itcasts.im.itcast.cn
    //人:lisi@im.itcast.cn
    
    //如果jidStr不包含"@im.itcast.cn",则是房间
    if (![aRecent.bareJidStr containsString:@"@im.zhigong.com"]) {
        
        //跳转群聊的线
        [self performSegueWithIdentifier:@"groupchat" sender:aRecent];

    }else{
        //跳转单聊的线
        [self performSegueWithIdentifier:@"chat" sender:aRecent];
    
    }
}

#pragma mark - XMPPStreamDelegate

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{

    //刷新数据
    [self fetchData];
}

#pragma mark - XMPPvCardAvatarDelegate
/**
 * 收到头像更新
 */
- (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(UIImage *)photo forJID:(XMPPJID *)jid{
    
    //刷新数据
    [self fetchData];
    
}


@end
